<?php

declare(strict_types=1);

namespace App\Api\Service;

use App\Model\Lessee;
use Hyperf\Contract\LengthAwarePaginatorInterface;
use Hyperf\DbConnection\Db;

class LesseeService
{
    /**
     * 承租人列表
     * @return LengthAwarePaginatorInterface
     */
    public function index(): LengthAwarePaginatorInterface
    {
        // 查询
        $res = Lessee::query()
            ->where('member_id', api_member_id())
            ->latest('is_default')
            ->latest('id')
            ->paginate();

        // 组装数据
        /** @var Lessee $model */
        foreach ($res as $model) {
            $model->setVisible(['id', 'name', 'phone', 'id_card', 'is_default']);
        }

        return $res;
    }

    /**
     * 添加承租人
     * @param array $params
     * @return void
     */
    public function store(array $params): void
    {
        // 用户ID
        $memberId = api_member_id();

        // 是否默认
        $count = Lessee::query()
            ->where('member_id', $memberId)
            ->count();
        $isDefault = $count > 0 ? Lessee::DISABLE : Lessee::ENABLE;

        // 创建承租人
        Lessee::create([
            'member_id' => $memberId,
            'name' => $params['name'],
            'phone' => $params['phone'],
            'id_card' => $params['id_card'],
            'is_default' => $isDefault,
        ]);
    }

    /**
     * 修改承租人
     * @param mixed $id
     * @param array $params
     * @return void
     */
    public function update(mixed $id, array $params): void
    {
        // 查询
        $lessee = Lessee::query()
            ->where('id', $id)
            ->where('member_id', api_member_id())
            ->firstOrFail();

        // 更新
        $lessee->name = $params['name'];
        $lessee->phone = $params['phone'];
        $lessee->id_card = $params['id_card'];
        $lessee->save();
    }

    /**
     * 更新承租人默认地址
     * @param mixed $id
     * @return void
     */
    public function updateDefault(mixed $id): void
    {
        // 查询
        $lessee = Lessee::query()
            ->where('id', $id)
            ->where('member_id', api_member_id())
            ->firstOrFail();
        if ($lessee->is_default === Lessee::ENABLE) {
            return;
        }

        Db::transaction(function () use ($lessee) {
            // 其他设置为非默认
            Lessee::query()
                ->where('member_id', $lessee->member_id)
                ->where('id', '<>', $lessee->id)
                ->update([
                    'is_default' => Lessee::DISABLE,
                ]);

            // 更新
            $lessee->is_default = Lessee::ENABLE;
            $lessee->save();
        });
    }

    /**
     * 删除承租人
     * @param mixed $id
     * @return void
     */
    public function destroy(mixed $id): void
    {
        // 删除
        Lessee::query()
            ->where('id', $id)
            ->where('member_id', api_member_id())
            ->firstOrFail()
            ->delete();
    }
}
